import React, { useState, useEffect, useRef } from 'react';

const TypeWriter = ({
    text,
    speed = 50,
    showCursor = false,
    onComplete,
    shouldStart = false
}) => {
    const [displayText, setDisplayText] = useState('');
    const intervalRef = useRef(null);
    const indexRef = useRef(0);
    const hasStartedRef = useRef(false);

    useEffect(() => {
        // 只有在shouldStart为true且还没开始时才开始打字
        if (!shouldStart || !text || hasStartedRef.current) {
            return;
        }

        console.log('开始打字动画:', text);
        hasStartedRef.current = true;

        // 清除之前的定时器
        if (intervalRef.current) {
            clearInterval(intervalRef.current);
        }

        // 重置状态
        setDisplayText('');
        indexRef.current = 0;

        // 开始打字动画
        intervalRef.current = setInterval(() => {
            if (indexRef.current < text.length) {
                setDisplayText(text.substring(0, indexRef.current + 1));
                indexRef.current++;
            } else {
                // 打字完成
                clearInterval(intervalRef.current);
                intervalRef.current = null;
                if (onComplete) {
                    onComplete();
                }
            }
        }, speed);

        // 清理函数
        return () => {
            if (intervalRef.current) {
                clearInterval(intervalRef.current);
            }
        };
    }, [shouldStart, text, speed]);

    return (
        <span className="typewriter">
            {displayText}
            {showCursor && indexRef.current < text.length && (
                <span className="typewriter-cursor">|</span>
            )}
        </span>
    );
};

export default TypeWriter;
